package top.ruanlitao.shortlink.project.service.impl;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import top.ruanlitao.shortlink.project.service.UrlTitleService;
import top.ruanlitao.shortlink.project.toolkit.WebsiteFetcherUtil;

import java.io.IOException;

/**
 * URL 标题接口实现层
 */
@Service
@Slf4j
public class UrlTitleServiceImpl implements UrlTitleService {

    public static void main(String[] args) throws IOException {
        Connection connection = Jsoup.connect("https://www.jsoup.org");
        Document document = connection.get();
        String title = document.title();
        System.out.println(title);
    }

    @SneakyThrows
    @Override
    public String getTitleByUrl(String url) {
        /*URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try {
                Document document = Jsoup.connect(url).get();
                return document.title();
            } catch (Throwable ex) {
                log.error("网址 {} 获取 title 失败，默认返回空字符串", url);
                return "";
            }
        }
        return "Error while fetching title.";*/
        return WebsiteFetcherUtil.getWebsiteTitle(url);
    }
}